package chaoyue.study.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelWrite {
    public static void main(String[] args) throws Exception {
        // 创建FileChannel
        RandomAccessFile accessFile = new RandomAccessFile("/Users/chaoyue/Downloads/demo.txt", "rw");
        FileChannel channel = accessFile.getChannel();
        // 创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        String data = "data:written by nio";
        // 写入数据
        buffer.put(data.getBytes());
        buffer.flip();
        while (buffer.hasRemaining()) {
            channel.write(buffer);
        }
        // 关闭channel
        channel.close();
        accessFile.close();
    }
}
